﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;

namespace LDAPOfficeTool
{
    public partial class LDAPOfficeToolRibbon
    {
        public class DocumentState
        {
            public Word.Document Document { get; set; }
            public LDAPTaskPane Control { get; set; }
            public Microsoft.Office.Tools.CustomTaskPane TaskPane { get; set; }
        }

        public readonly List<DocumentState> DocumentStates = new List<DocumentState>();



        public void HandleDocumentOpen(Word.Document Doc)
        {
            var taskPaneOffen = false;

            DocumentStates.ForEach((state) =>
            {

                string fullName = null;
                try
                {
                    fullName = state.Document.FullName;
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    RemoveDocumentState(state);
                }

                if (state.Document == Doc || fullName == Doc.FullName)
                {
                    if (state.Control.Visible == false || state.Control.Created == false || state.TaskPane.Visible == false)
                    {
                        RemoveDocumentState(state);
                    }
                    else
                    {
                        taskPaneOffen = true;
                    }

                }

            });

            if (taskPaneOffen)
                return;

            var control = new LDAPTaskPane();
            var taskPane = ThisAddIn.Instance.CustomTaskPanes.Add(control, "Suche in LDAP.gv.at", Doc.ActiveWindow);
            taskPane.Control.Dock = System.Windows.Forms.DockStyle.Fill;
            taskPane.DockPosition = Office.MsoCTPDockPosition.msoCTPDockPositionRight;
            taskPane.Visible = true;
            // bobic adjusts width
            taskPane.Width = 280;
            DocumentStates.Add(new DocumentState { Document = Doc, Control = control, TaskPane = taskPane });
        }

        private void RemoveDocumentState(DocumentState state)
        {
            try
            {
                state.TaskPane.Visible = false;
            }
            catch (System.Runtime.InteropServices.COMException)
            {
            }

           ThisAddIn.Instance.CustomTaskPanes.Remove(state.TaskPane);
            DocumentStates.Remove(state);
        }

        private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
        {

        }

        private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            HandleDocumentOpen(ThisAddIn.Instance.Application.ActiveDocument);
        }
    }
}
